package com.shawn.spring.boot.mybatis.handle;

import com.shawn.spring.boot.mybatis.constants.BaseEnum;
import com.shawn.spring.boot.mybatis.constants.MenuTypeEnum;
import com.shawn.spring.boot.mybatis.util.EnumUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * @author shawn
 * @since 2020/8/30
 */
public class EnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum> {

  @Override
  public void setNonNullParameter(
      PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
    ps.setInt(i, parameter.getCode());
  }

  @Override
  public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
    int code = rs.getInt(columnName);
    return rs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
  }

  @Override
  public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    int code = rs.getInt(columnIndex);
    return rs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
  }

  @Override
  public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    int code = cs.getInt(columnIndex);
    return cs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
  }
}
